using System;
using System.Collections;
using Naptime.Extensions;
using UnityEngine;
using UnityEngine.SceneManagement;
using UnityEngine.UI;
using Voodoo.GameOps;
using Voodoo.Pattern;
using Voodoo.Pattern.Random;

public class GameManager : SingletonMB<GameManager>
{
	[SerializeField]
	private GameObject _menu;

	[SerializeField]
	private GameObject _game;

	[SerializeField]
	private GameObject _outOf;

	[SerializeField]
	private GameObject _outOfOilRv;

	[SerializeField]
	private GameObject _outOfMoneyRv;

	[SerializeField]
	private GameObject _bonusLevelRv;

	[SerializeField]
	private GameObject _bonusLevelBanner;

	[SerializeField]
	private Animator _camAnim;

	[SerializeField]
	private RectTransform _joy;

	[SerializeField]
	public bool IsDuelMode;

	[SerializeField]
	private PrestigePanel prestigePanel;

	[SerializeField]
	private FinishScreen _finish;

	[SerializeField]
	private Transform _sky;

	[SerializeField]
	private Image _1;

	[SerializeField]
	private Image _2;

	[SerializeField]
	private Text _3;

	[SerializeField]
	private Text _earned;

	[SerializeField]
	private GameObject _noAdsButton;

	[SerializeField]
	private GameObject _duelModeUnlocked;

	public GameObject PlayButton;

	public Oil currentOilUI;

	public Cam Cam;

	public bool finised;

	private int _gameCount;

	public CoinFxReceiver _CashReceiver;

	public int moneySpent;

	public bool canMove;

	public bool windowActive;

	private const string GAME_COUNT_PREF = "VoodooBucketGameCount";

	public Control Control;

	public GameplayAudio GameplayAudio;

	public UIAudio UIAudio;

	public GameplayHaptic GameplayHaptic;

	private GameProperties gameProperties;

	public Action OnGameStart;

	public Action OnGameEnd;

	public bool BoostLevel;

	private const string c_IsDrawingLevelKey = "IsDrawingLevelKey";

	public PseudoPool namePool;

	private AsyncOperation _asyncTransition;

	public bool EcoMode;

	public float EcoTimer = 30f;

	public bool AnyWindowActive
	{
		get
		{
			return windowActive;
		}
		set
		{
			windowActive = value;
		}
	}

	public bool CanMove
	{
		get
		{
			return canMove;
		}
		set
		{
			canMove = value;
		}
	}

	public int DeltaMoney => Mathf.CeilToInt(UnityEngine.Object.FindObjectOfType<Sell>().deltaMoney);

	public int MoneySpent
	{
		get
		{
			return moneySpent;
		}
		set
		{
			moneySpent = value;
			NintendoPlayerPrefs.SetFloat("MoneySpent", moneySpent);
		}
	}

	public int Money => (int)NintendoPlayerPrefs.GetFloat("Money", 0f);

	public int PrestigePoints => (int)NintendoPlayerPrefs.GetFloat("PrestigePoints", 0f);

	public int LastLevelIndex
	{
		get
		{
			return NintendoPlayerPrefs.GetInt("LastLevelIndex", 0);
		}
		set
		{
			NintendoPlayerPrefs.SetInt("LastLevelIndex", value);
		}
	}

	public bool BetterNoAds => NintendoPlayerPrefs.GetInt("BetterNoAds", 0) == 1;

	private int _totalGameCount
	{
		get
		{
			return NintendoPlayerPrefs.GetInt("VoodooBucketGameCount", 0);
		}
		set
		{
			NintendoPlayerPrefs.SetInt("VoodooBucketGameCount", value);
		}
	}

	public Joystick Joystick { get; internal set; }

	public bool IsDrawingLevel
	{
		get
		{
			return NintendoPlayerPrefs.GetInt("IsDrawingLevelKey") != 0;
		}
		set
		{
			NintendoPlayerPrefs.SetInt("IsDrawingLevelKey", value ? 1 : 0);
		}
	}

	public int ReturnCount
	{
		get
		{
			return NintendoPlayerPrefs.GetInt("Return_From_Game", 0);
		}
		set
		{
			NintendoPlayerPrefs.SetInt("Return_From_Game", value);
		}
	}

	public int Currentlevel => NintendoPlayerPrefs.GetInt("Level", 0);

	public Action OnBoughtBetterNoAds { get; internal set; }

	internal void ActivateRenewable()
	{
		EcoMode = true;
		EcoTimer = 30f;
		StartGame();
	}

	private void Awake()
	{
		NintendoPlayerPrefs.SetInt("Level", NintendoPlayerPrefs.GetInt("Level", 0));
		SetCameraAnimationSide();
		EcoMode = false;
		OnGameEnd = (Action)Delegate.Combine(OnGameEnd, new Action(TrackOnGameFinish));
	}

	public void ReplaceControls(Joystick joystick, bool tapControl = false)
	{
		Joystick = joystick;
		Joystick.gameObject.SetActive(value: false);
		if (tapControl)
		{
			Control.ReplaceJoystick(GetComponent<TapControl>());
			GameplayAudio.ReplaceJoystick(GetComponent<TapControl>());
			GetComponent<TapControl>().tapControlChosen = true;
			if (SingletonMB<DuelModeManager>.Instance == null)
			{
				GameObject.Find("Oil").GetComponent<Oil>().joystick = GetComponent<TapControl>();
			}
			joystick.GetComponent<RectTransform>().anchoredPosition = new Vector2(-1000f, 0f);
		}
		else
		{
			Control.ReplaceJoystick(joystick);
			GameplayAudio.ReplaceJoystick(joystick);
		}
		GameplayHaptic = GetComponent<GameplayHaptic>();
	}

	public void SetCameraAnimationSide(LevelPosType type = LevelPosType.Right)
	{
		_camAnim.SetBool("right", type == LevelPosType.Right);
		_camAnim.SetBool("left", type == LevelPosType.Left);
		_camAnim.SetBool("top", type == LevelPosType.Top);
		_camAnim.SetBool("bottom", type == LevelPosType.Arch);
	}

	private void Start()
	{
		AnyWindowActive = false;
		moneySpent = 0;
		CanMove = false;
		NintendoPlayerPrefs.SetFloat("Money", Mathf.Max(0f, NintendoPlayerPrefs.GetFloat("Money")));
		MoneySpent = (int)NintendoPlayerPrefs.GetFloat("MoneySpent", 0f);
		if (_duelModeUnlocked != null)
		{
			_duelModeUnlocked.SetActive(value: false);
		}
		if (SingletonMB<ShopCanvas>.Instance != null)
		{
			SingletonMB<ShopCanvas>.Instance.Show();
			_menu.SetActive(value: true);
		}
		_sky.localPosition = new Vector3(UnityEngine.Random.Range(-13f, 1.4f), 7.57f, 1.43f);
		if (Preloader.ABTestConfig.Boosters)
		{
			UnityEngine.Object.FindObjectOfType<BoosterSpawn>().Refrash();
		}
		if (Preloader.OptimizationConfig.IsEnabled)
		{
			Time.maximumDeltaTime = 0.06f;
			Physics.defaultSolverIterations = 2;
		}
		UnityEngine.Object.FindObjectOfType<BubbleBonusManager>()?.ShowBubble();
		gameProperties = GetComponent<GameProperties>();
		GetComponent<Upgrade>().UpdateAllStage();
		StartCoroutine(FirstRunRoutine());
	}

	private IEnumerator FirstRunRoutine()
	{
		if (!NintendoPlayerPrefs.HasKey("FIRST_RUN_KEY"))
		{
			yield return new WaitForEndOfFrame();
			yield return new WaitForEndOfFrame();
			NintendoPlayerPrefs.SetFloat("Money", 0f);
			NintendoPlayerPrefs.SetBool("FIRST_RUN_KEY", value: true);
			NintendoPlayerPrefs.Save();
			SingletonMB<Shop>.Instance.CheckButtons();
		}
	}

	private void FirstLaunch()
	{
		StartGame();
		NintendoPlayerPrefs.SetInt("First", 1);
	}

	public void OilLostNoRV()
	{
		if (finised)
		{
			return;
		}
		UIAudio.PlaySound(UISoundType.LostFuel);
		GameplayHaptic.PlayHaptic(HapticType.LostFuel);
		if (Preloader.BetterWinScreen.IsEnabled)
		{
			SingletonMB<MessageCenter>.Instance.ShowEndScreen(EndScreenMode.LevelFailed, delegate
			{
				GetXMoney();
			}, delegate
			{
				FinishGame();
				_outOf.SetActive(value: false);
			});
		}
		else
		{
			_outOf.SetActive(value: true);
			_game.SetActive(value: false);
			StartCoroutine(f());
			_earned.text = "+" + Mathf.CeilToInt(UnityEngine.Object.FindObjectOfType<Sell>().deltaMoney) + "$";
		}
		IEnumerator f()
		{
			yield return new WaitForSeconds(0.5f);
			FinishGame();
			yield return new WaitForSeconds(0.9f);
			_outOf.SetActive(value: false);
		}
	}

	public void OilLostOilRV()
	{
		GetComponent<TapControl>().StopControl();
		if (finised)
		{
			return;
		}
		_game.SetActive(value: false);
		UIAudio.PlaySound(UISoundType.LostFuel);
		GameplayHaptic.PlayHaptic(HapticType.LostFuel);
		if (Preloader.BetterWinScreen.IsEnabled)
		{
			SingletonMB<MessageCenter>.Instance.ShowEndScreen(EndScreenMode.NoOIl, delegate
			{
				FIllTank(afterMiniGame: false);
			}, delegate
			{
				EndGame();
			});
		}
		else
		{
			CanMove = false;
			_outOfOilRv.SetActive(value: true);
			_outOfOilRv.GetComponent<NoGasMiniGame>().Setup();
		}
	}

	public void ShowBonusLevelRVScreen()
	{
		if (!finised)
		{
			_bonusLevelRv.SetActive(value: true);
			_game.SetActive(value: false);
			UIAudio.PlaySound(UISoundType.LostFuel);
			GameplayHaptic.PlayHaptic(HapticType.LostFuel);
		}
	}

	public void LoadIntoDuel()
	{
		SceneManager.LoadScene("DuelGame");
	}

	public void LoadIntoMain()
	{
		SceneManager.LoadScene("GamePlay");
	}

	internal void StartLoadIntoTransition()
	{
		_asyncTransition = SceneManager.LoadSceneAsync("GamePlay_Transition");
		_asyncTransition.allowSceneActivation = false;
	}

	public void LoadIntoTransition()
	{
		if (_asyncTransition != null)
		{
			_asyncTransition.allowSceneActivation = true;
		}
		else
		{
			SceneManager.LoadScene("GamePlay_Transition");
		}
	}

	internal void OpponentUpgraded()
	{
		Head[] array = UnityEngine.Object.FindObjectsOfType<Head>();
		for (int i = 0; i < array.Length; i++)
		{
			array[i].SetKinematic(active: false);
		}
	}

	public void BackToMenu()
	{
		if (!finised)
		{
			_outOf.SetActive(value: true);
			_game.SetActive(value: false);
			StartCoroutine(f());
			_earned.text = "+" + Mathf.CeilToInt(UnityEngine.Object.FindObjectOfType<Sell>().deltaMoney) + "$";
			currentOilUI.UpdateValues();
			_1.color = new Color(0f, 0f, 0f, 0f);
			_2.color = new Color(0f, 0f, 0f, 0f);
			_3.color = new Color(0f, 0f, 0f, 0f);
			currentOilUI.StopSpend();
			if (Preloader.ShowLevelAtBeginning.IsEnabled || Preloader.Transition.IsEnabled)
			{
				Cam.ShowWholeLevel();
			}
			GetComponent<TapControl>().StopControl();
		}
		IEnumerator f()
		{
			yield return new WaitForSeconds(0.4f);
			FinishGame();
			yield return new WaitForSeconds(0.5f);
			yield return new WaitForSeconds(0.9f);
			_outOf.GetComponent<Animator>().SetBool("canContinue", value: false);
			_outOf.SetActive(value: false);
		}
	}

	public void FIllTank(bool afterMiniGame)
	{
		_outOfOilRv.SetActive(value: false);
		_game.SetActive(value: true);
		Oil oil = currentOilUI;
		oil.AnimateOil();
		if (afterMiniGame)
		{
			oil.RefillAfterMiniGame();
		}
		else
		{
			oil.UpdateValues();
		}
		oil.StartSpendingOil();
		GetComponent<TapControl>().StartControl();
	}

	public void GetXMoney()
	{
		int num = Mathf.CeilToInt(UnityEngine.Object.FindObjectOfType<Sell>().deltaMoney) * 2;
		NintendoPlayerPrefs.SetFloat("Money", NintendoPlayerPrefs.GetFloat("Money", 0f) + (float)num);
		UnityEngine.Object.FindObjectOfType<Money>().UpdateValue();
		EndGame();
	}

	private void Update()
	{
	}

	public void EndGame()
	{
		CanMove = false;
		_outOf.SetActive(value: false);
		_outOfOilRv.SetActive(value: false);
		_outOfMoneyRv.SetActive(value: false);
		_bonusLevelRv.SetActive(value: false);
		InventoryManager.Instance.AddMoney(DeltaMoney);
		if (DeltaMoney == 0)
		{
			InventoryManager.Instance.AddMoney(200f);
		}
		FinishGame();
	}

	private IEnumerator WaitForCameraAnim()
	{
		Cam.custom = Cam._head;
		Cam.customFOV = Cam.originalFOV;
		_camAnim.SetBool("isGame", value: true);
		yield return new WaitForSeconds(1f);
		SingletonMB<GameManager>.Instance.Cam.custom = null;
	}

	public void StartGame()
	{
		if (!finised && !AnyWindowActive)
		{
			Cam.custom = null;
			_1.color = new Color(1f, 1f, 1f, 1f);
			_2.color = new Color(1f, 1f, 1f, 1f);
			_3.color = new Color(0.5f, 0.5f, 0.5f, 1f);
			_outOf.SetActive(value: false);
			_menu.SetActive(value: false);
			_game.SetActive(value: true);
			SingletonMB<UIManager>.Instance.HideRightBtns();
			_outOfOilRv.GetComponent<NoGasMiniGame>().NewGame();
			UnityEngine.Object.FindObjectOfType<BubbleBonusManager>()?.DisableBubble();
			if (!SingletonMB<GameManager>.Instance.IsDuelMode)
			{
				currentOilUI.StartSpendingOil();
			}
			Head[] array = UnityEngine.Object.FindObjectsOfType<Head>();
			for (int i = 0; i < array.Length; i++)
			{
				array[i].SetKinematic(active: false);
			}
			if (SingletonMB<GameManager>.Instance.IsDuelMode || Preloader.ShowLevelAtBeginning.IsEnabled)
			{
				StartCoroutine(WaitForCameraAnim());
				SingletonMB<GameManager>.Instance.Cam.custom = null;
			}
			else
			{
				_camAnim.SetBool("isGame", value: true);
			}
			Joystick.gameObject.SetActive(value: true);
			GetComponent<TapControl>().StartControl();
			_joy.anchoredPosition = new Vector2(0f, _joy.anchoredPosition.y);
			OnGameStart?.Invoke();
			SingletonMB<ShopCanvas>.Instance.Hide();
			CanMove = true;
		}
	}

	public void PlayerUpgraded()
	{
		Joystick.gameObject.SetActive(value: true);
		GetComponent<TapControl>().StartControl();
		Head[] array = UnityEngine.Object.FindObjectsOfType<Head>();
		for (int i = 0; i < array.Length; i++)
		{
			array[i].SetKinematic(active: false);
		}
	}

	public void ContinueAfterMiniGame()
	{
		FIllTank(afterMiniGame: true);
		CanMove = true;
	}

	public void ShowPrestigePanel()
	{
		prestigePanel.Setup();
	}

	public void Prestige(int points)
	{
		NintendoPlayerPrefs.SetFloat("Money", 0f);
		NintendoPlayerPrefs.SetFloat("MoneySpent", 0f);
		NintendoPlayerPrefs.SetInt("Level", 0);
		NintendoPlayerPrefs.SetInt("__PrestigePerformed", 1);
		SingletonMB<Shop>.Instance.ResetAllSells();
		InventoryManager.Instance.AddPrestigePoints(points);
		MoneySpent = 0;
		GetComponent<Upgrade>().UpdateAllStage();
		SingletonMB<Shop>.Instance.CheckButtons();
		UnityEngine.Object.FindObjectOfType<Map>();
		MapCreatorEditor mapCreatorEditor = UnityEngine.Object.FindObjectOfType<MapCreatorEditor>();
		GetComponent<Progress>().SetLevelText(1);
		mapCreatorEditor.ResetCubes();
		mapCreatorEditor.GetCurrentLevel(0);
	}

	public void FinishGame()
	{
		CanMove = false;
		if (finised)
		{
			return;
		}
		if (NintendoPlayerPrefs.HasKey("__PrestigePerformed") && NintendoPlayerPrefs.GetInt("__PrestigePerformed", 0) == 1)
		{
			NintendoPlayerPrefs.SetInt("__PrestigePerformed", 0);
			UnityEngine.Object.FindObjectOfType<Money>().SetActive(active: false);
			UnityEngine.Object.FindObjectOfType<PrestigePointsCounter>().SetActive(active: false);
			SingletonMB<GameManager>.Instance.RestartLevelAfterComplete();
			return;
		}
		EcoMode = false;
		_gameCount++;
		_totalGameCount++;
		_game.SetActive(value: false);
		BoostLevel = false;
		currentOilUI.UpdateValues();
		GetComponent<Upgrade>().UpdateAllStage();
		GetComponent<TapControl>().StopControl();
		_camAnim.SetBool("isGame", value: false);
		GetComponent<Shop>()?.CheckButtons();
		SingletonMB<UIManager>.Instance.ShowRightBtns();
		MapCreatorEditor mapCreatorEditor = UnityEngine.Object.FindObjectOfType<MapCreatorEditor>();
		if (SingletonMB<BonusLevelManager>.Instance.IsBonusLevelActive || mapCreatorEditor.IsBonusLevel)
		{
			mapCreatorEditor.GenerateLevel();
		}
		UnityEngine.Object.FindObjectOfType<Map>()?.ResetMap();
		if (Preloader.BonusLevelConfig.IsEnabled)
		{
			UnityEngine.Object.FindObjectOfType<SkinApplicator>()?.ApplySkin();
		}
		_joy.anchoredPosition = new Vector2(-1000f, _joy.anchoredPosition.y);
		if (SingletonMB<BonusLevelManager>.Instance.IsBonusLevelActive || UnityEngine.Object.FindObjectOfType<MapCreatorEditor>().IsBonusLevel)
		{
			Invoke("ResetProgress", 0.9f);
		}
		else
		{
			ResetProgress();
		}
		UnityEngine.Object.FindObjectOfType<Cam>().SetZeroPos();
		UnityEngine.Object.FindObjectOfType<Sell>().ResetMultyplyer();
		if (Preloader.ABTestConfig.Boosters)
		{
			UnityEngine.Object.FindObjectOfType<BoosterSpawn>().Refrash();
		}
		UnityEngine.Object.FindObjectOfType<PowerTimer>().FinishPower();
		UnityEngine.Object.FindObjectOfType<BubbleBonusManager>()?.ShowBubble();
		OnGameEnd?.Invoke();
	}

	private void TrackOnGameFinish()
	{
	}

	private void ShowLoadingsScreen()
	{
	}

	public void TryShowSkinUnlock()
	{
		if (!string.IsNullOrEmpty(SkinMissionController.UnlockedItem))
		{
			Item item = InventoryManager.Instance.GetItem(SkinMissionController.UnlockedItem);
			if (item != null)
			{
				SingletonMB<SkinContainer>.Instance.UnlockPopUp.Show(item);
				InventoryManager.Instance.SelectItem(item);
			}
			SkinMissionController.UnlockedItem = null;
		}
		else
		{
			TryShowDuelUnlocked();
		}
	}

	public void TryShowDuelUnlocked()
	{
		if (_duelModeUnlocked != null)
		{
			_duelModeUnlocked.SetActive(value: false);
			if (Preloader.DuelFightModeConfig.IsEnabled && NintendoPlayerPrefs.GetInt("Level", 0) > 0 && NintendoPlayerPrefs.GetInt("Duel_Unlock_Shown", 0) == 0)
			{
				NintendoPlayerPrefs.SetInt("Duel_Unlock_Shown", 1);
				_duelModeUnlocked.SetActive(value: true);
			}
		}
	}

	private void ResetProgress()
	{
		ReturnCount++;
		if (Preloader.Transition.IsEnabled && SceneManager.GetActiveScene().name != "GamePlay_Transition")
		{
			LoadIntoTransition();
			return;
		}
		_menu.SetActive(value: true);
		UnityEngine.Object.FindObjectOfType<Progress>().ResetCount();
		SingletonMB<ShopCanvas>.Instance.Show();
	}

	public void FinishLevel()
	{
		if (finised)
		{
			return;
		}
		GameplayHaptic.PlayHaptic(HapticType.Win);
		finised = true;
		UIAudio.PlaySound(UISoundType.Win);
		if (!SingletonMB<BonusLevelManager>.Instance.IsBonusLevelActive && !UnityEngine.Object.FindObjectOfType<MapCreatorEditor>().IsBonusLevel)
		{
			NintendoPlayerPrefs.SetInt("Level", NintendoPlayerPrefs.GetInt("Level", 0) + 1);
			MapCreatorEditor mapCreatorEditor = UnityEngine.Object.FindObjectOfType<MapCreatorEditor>();
			LastLevelIndex = mapCreatorEditor.thisLevelIndex;
			MoneySpent = 0;
			SingletonMB<SkinMissionController>.Instance.ProgressMission(SkinMissionType.CompleteLevel, 1);
			if (!Preloader.Transition.IsEnabled)
			{
				GetComponent<Shop>().ResetAllSells();
			}
		}
		int additionalMIney = 0;
		if (Preloader.BetterWinScreen.IsEnabled && SingletonMB<DuelModeManager>.Instance == null)
		{
			Debug.Log("Finish2");
			SingletonMB<MessageCenter>.Instance.ShowEndScreen(EndScreenMode.LevelCompelete, delegate
			{
				Debug.Log("Finish3");
				additionalMIney = Mathf.CeilToInt(UnityEngine.Object.FindObjectOfType<Sell>().deltaMoney) * 2;
				NintendoPlayerPrefs.SetFloat("Money", NintendoPlayerPrefs.GetFloat("Money", 0f) + (float)additionalMIney);
				UnityEngine.Object.FindObjectOfType<Money>().UpdateValue();
				StartCoroutine(RestartLevel(1f, needInterstitial: false));
			}, delegate
			{
				StartCoroutine(RestartLevel(0f, needInterstitial: true));
			});
		}
		else if (SingletonMB<DuelModeManager>.Instance != null)
		{
			Debug.Log("Finish4");
			GetComponent<TapControl>().StopControl();
			SingletonMB<DuelModeManager>.Instance.OnGameFinished();
		}
		else if (Preloader.Transition.IsEnabled)
		{
			Debug.Log("Finish5");
			SingletonMB<TransitionAnimationController>.Instance.StartTransition();
		}
		else
		{
			_finish.Setup(NintendoPlayerPrefs.GetInt("Level", 0), additionalMIney + ((DeltaMoney == 0) ? 200 : DeltaMoney));
		}
		static IEnumerator RestartLevel(float delay, bool needInterstitial)
		{
			Debug.Log("Restart");
			yield return new WaitForSeconds(delay);
			if (Preloader.Transition.IsEnabled)
			{
				SingletonMB<TransitionAnimationController>.Instance.StartTransition();
			}
			else if (Preloader.CityBuilderConfig.IsEnabled)
			{
				SceneManager.LoadScene("CityBuilder");
			}
			else if (Preloader.DrawYourOwnLevel.IsEnabled)
			{
				SceneManager.LoadScene("Drawing");
			}
			else
			{
				SceneManager.LoadSceneAsync("GamePlay");
			}
		}
	}

	public void RestartLevelAfterComplete()
	{
		SceneManager.LoadScene("GamePlay");
		NintendoPlayerPrefs.SetInt("__PrestigePerformed", 0);
	}

	public void FinishBonusLevel()
	{
		if (!finised)
		{
			GameplayHaptic.PlayHaptic(HapticType.Win);
			UIAudio.PlaySound(UISoundType.Win);
			StartCoroutine(RestartLevel());
		}
		static IEnumerator RestartLevel()
		{
			yield return new WaitForSeconds(2f);
			SceneManager.LoadSceneAsync("GamePlay");
		}
	}
}
